home *** CD-ROM | disk | FTP | other *** search
- Path: wkaufman.us.oracle.com!wkaufman
- From: wkaufman@wkaufman.us.oracle.com (William Kaufman)
- Newsgroups: comp.lang.c
- Subject: Re: Determining the length of an int in string form
- Date: 14 Mar 1996 02:05:37 GMT
- Organization: Oracle Corporation, Redwood Shores CA
- Message-ID: <4i7uth$qph@inet-nntp-gw-1.us.oracle.com>
- References: <3146D058.DD7@cbm.com>
- NNTP-Posting-Host: wkaufman.us.oracle.com
-
- In article <3146D058.DD7@cbm.com> Dave Payne <paynedc@cbm.com> writes:
- ] Consider this:
- ]
- ] I have a variable of type int, and I would like to use the sprintf()
- ] function to write this variable to a string. However, I want to
- ] dynamically allocate the space for the string, and only malloc enough
- ] space to hold the int.
-
- For any binary number, the number of decimal digits is about 0.3 the
- number of binary digits. (It's actually log10(2), but 0.3 is close
- enough.) So, for an int, that's about
-
- int i;
-
- (sizeof(i) * CHAR_BIT * 10) / 3
-
- (For maximum accuracy, use ints, multiply first, then divide.)
-
- Add in a character for the "-" sign, and another for the '\0' at the
- end, and maybe another one just for the fact that I rounded log10(2)
- down to 0.3, and you'll have overshot by about a character, since I
- didn't account for the fact that it's a signed quantity and the maximum
- is a bit smaller than (sizeof(int) * CHAR_BIT). But, hey, what's a
- character between friends?
-
- The nice thing about the above calculation is that it's an integral
- constant: you can even use it in an array declaration.
-
- If you want it to perfectly match the integer you've got, rather
- than any integer you may get, you could do something like
- (size_t)(log10((double)i)) and add in the extra characters listed above.
- (Mind you, I'm not convinced that the extra time calling log10() is
- worth saving a few bytes per string--depending on how many strings
- you've got.)
-
- -- Bill K.
-
- Bill Kaufman, | "Patience is a virtue. Seersucker is a fabric."
- wkaufman@us.oracle.com | -- Bazooka Joe
-